<template>
  <view class="
      kui-w-120
      kui-h-8
      kui-bg-gray-200
      kui-flex
      kui-justify-between
      kui-p-2
      kui-rounded
      kui-flex
      kui-items-center
    " :class="circle ? 'kui-rounded-full' : ''" :style="{
      backgroundColor: data.backgroundColor,
    }">
    <template v-for="(item, index) in data.data" :key="index">
      <!-- #ifdef MP-WEIXIN -->
      <view class="kui-p-2 kui-m-px kui-rounded tabs-item-text kui-z-10" :class="circle ? 'kui-rounded-full' : ''"
        :data-id="index" :data-duration="duration" @tap="tabs.change">
        <text :class="!item.active ? 'kui-text-gray-500' : ''" :style="{
          color: item.active ? data.activeColor : inactiveColor,
        }">{{ item.txt }}</text>
      </view>
      <!-- #endif -->
      <!-- #ifndef MP-WEIXIN -->
      <view class="kui-p-2 kui-m-px kui-rounded tabs-item kui-z-10" :class="circle ? 'kui-rounded-full' : ''"
        @tap="onChange(item)">
        <text :class="!item.active ? 'kui-text-gray-500' : ''" :style="{
          color: item.active ? data.activeColor : data.inactiveColor,
        }">{{ item.txt }}</text>
      </view>
      <!-- #endif -->
    </template>
    <view :animation="data.animationData" class="
        kui-bg-white kui-shadow-md kui-p-2 kui-rounded
        tabs-item
        kui-absolute
      " :class="circle ? 'kui-rounded-full' : ''" :style="{
        backgroundColor: data.activeBackgroundColor,
      }" v-if="data.currentTab">
      <text class="kui-text-transparent">{{ data.currentTab.txt }}</text>
    </view>
  </view>
</template>
<script module="tabs" lang="wxs">
function change(e, ins) {
  var instance = ins.selectComponent('.tabs-item');

  instance.setStyle({
    'transform': 'translateX(' + (e.currentTarget.offsetLeft - 23) + 'px)',
    'transition-duration': e.currentTarget.dataset.duration + 'ms'
  })

  ins.callMethod('wxsUpdateData', {
    index: e.currentTarget.dataset.id
  })
}

module.exports = {
  change: change
}
</script>

<script lang="ts" setup name="kui-tabs">
/**
 * Tabs 选项卡组件
 * @description tabs滑动切换组件
 * @property {Array} list 选项卡数组
 * @property {Boolean} circle = [true/false] 是否为圆角
 * 	@value true 是
 * 	@value false 否
 * @property {String} background-color 背景色
 * @property {String} inactive-color 未激活文字颜色
 * @property {String} active-color 激活文字颜色
 * @property {String} active-bg-color 激活背景色
 * @property {Number} duration 切换动画时间，单位ms
 * @property {String} mode = [light/dark/system] 页面模式
 * 	@value light 亮色模式
 * 	@value dark 暗色模式
 * 	@value system 跟随系统
 */
import { reactive, getCurrentInstance } from "vue";
const { proxy }: any = getCurrentInstance();
const $theme = proxy.$theme;

interface Props {
  list?: any;
  circle?: boolean;
  backgroundColor?: string;
  inactiveColor?: string;
  activeColor?: string;
  activeBackgroundColor?: string;
  duration?: number;
  mode?: string;
}
const props = withDefaults(defineProps<Props>(), {
  list: [],
  circle: false,
  backgroundColor: "",
  inactiveColor: "",
  activeColor: "",
  activeBackgroundColor: "",
  duration: 400,
  mode: "light",
});
const data = reactive({
  data: [],
  animationData: {},
  animation: {},
  active: false,
  index: 0,
  selectRect: [],
  currentTab: null,
  mode: props.mode,
  backgroundColor: props.backgroundColor
    ? props.backgroundColor
    : $theme.colors["light"]["grey"][2],
  activeBackgroundColor: props.activeBackgroundColor
    ? props.activeBackgroundColor
    : $theme.colors["light"]["grey"][2],
  activeColor: props.activeColor
    ? props.activeColor
    : $theme.colors["light"]["grey"][9],
  inactiveColor: props.inactiveColor
    ? props.inactiveColor
    : $theme.colors["light"]["grey"][5],
});

const changeMode = () => {
  data.backgroundColor = data.mode == 'light' ? props.backgroundColor : (props.backgroundColor ? uni.kviewUIColor.generate(props.backgroundColor, {dark: true, list: false, index: 6}) : $theme.colors['dark']['grey'][3]);
  data.activeBackgroundColor = data.mode == 'light' ? props.activeBackgroundColor : (props.activeBackgroundColor ? uni.kviewUIColor.generate(props.activeBackgroundColor, {dark: true, list: false, index: 6}) : $theme.colors['dark']['grey'][2]);
  data.activeColor = data.mode == 'light' ? props.activeColor : (props.activeColor ? uni.kviewUIColor.generate(props.activeColor, {dark: true, list: false, index: 6}) : $theme.colors['dark']['grey'][8]);
  data.inactiveColor = data.mode == 'light' ? props.inactiveColor : (props.inactiveColor ? uni.kviewUIColor.generate(props.inactiveColor, {dark: true, list: false, index: 6}) : $theme.colors['dark']['grey'][6]);
};

const init = () => {
  props.list.forEach((item, idx) => {
    let active = idx == 0;
    data.data.push({
      id: idx,
      txt: item,
      active: active,
      left: 0,
      right: 0,
    });
    setTimeout(() => {
      console.log(data.selectRect[idx], 2222);
      // #ifndef MP-WEIXIN
      data.data[idx].left = data.selectRect[idx].left;
      data.data[idx].right = data.selectRect[idx].right;
      // #endif
    }, 600);
    if (active) {
      data.currentTab = {
        id: idx,
        txt: item,
        active: active,
        left: 0,
        right: 0,
      };
    }
    // 样式处理
    changeMode();
  });
};

init();
const query = uni.createSelectorQuery().in(proxy);
setTimeout(() => {
  query
    .selectAll(".tabs-item")
    .boundingClientRect((res) => {
      data.selectRect = res;
      data.selectRect = [...data.selectRect];
    })
    .exec();
}, 300);
// 监听暗黑模式
uni.$on("changeMode", (e) => {
  data.mode = e;
  changeMode();
});

const wxsUpdateData = (e) => {
  let idx = e.index;
  data.data.forEach((item, index) => {
    item.active = index == idx ? true : false;
  });
};

const onChange = (e) => {
  if (!e.active) {
    data.data.forEach((item, index) => {
      item.active = item.id == e.id;
    });
    data.active = true;
    data.animation = uni.createAnimation({
      duration: props.duration,
      timingFunction: 'ease'
    });
    data.animation.translateX(e.left - 23).step();
    data.animationData = data.animation.export();
    data.index = e.id;
    setTimeout(() => {
      data.active = false;
      data.currentTab = e;
    }, 200);
  }
};

// 把wxs需要的方法暴露出去方便wxs调用
defineExpose({
  wxsUpdateData
});
</script>

<style>
</style>